<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-17 22:36:17
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-18 10:53:10
 * @FilePath: /free-learning/src/views/course-manage/course-user/index.vue
 * @Description: 课程观看用户页面
-->
<script setup lang="ts">
import { ref, onMounted } from "vue";
import type { CourseUser, ByConsultantIdPageQuery } from "@/api/course/course-user/type";
import { queryByConsultantPage } from "@/api/course/course-user";
import { ElMessage } from "element-plus";
import { getCourseListByConsultantId } from "@/api/course/course-mange";
import type { CourseInfo } from "@/api/course/course-mange/type";
import { useUserStore } from "@/store";
import { CourseCategoryListVO } from "@/api/system/course-category/type";
import { getList } from "@/api/system/course-category";
import UserAPI from "@/api/system/user";
defineOptions({
  name: "CourseUser",
});
const userStrore = useUserStore();

// 查询条件
const queryForm = ref<Partial<ByConsultantIdPageQuery>>({
  courseId: undefined,
  consultantId:
    userStrore.userInfo.roles.includes("ADMIN") || userStrore.userInfo.roles.includes("ROOT")
      ? undefined
      : userStrore.userInfo.userId,
  status: undefined,
  learningDurationSort: undefined,
  progressSort: undefined,
  pageSize: 10,
  pageNum: 1,
});
const courseList = ref<CourseInfo[]>([]);
const queryCourseList = async () => {
  if (userStrore.userInfo.roles.includes("ADMIN") || userStrore.userInfo.roles.includes("ROOT")) {
    const res = await getCourseListByConsultantId({ consultantId: undefined });
    courseList.value = res;
  } else {
    const res = await getCourseListByConsultantId({
      consultantId: userStrore.userInfo.userId,
    });
    courseList.value = res;
  }
};
const categoryOptions = ref<CourseCategoryListVO[]>([]);
// 获取课程分类
const fetchCategories = async () => {
  try {
    const res = await getList();
    categoryOptions.value = res;
  } catch (error) {
    ElMessage.error("获取课程分类失败");
  }
};
// 表格数据
const tableData = ref<CourseUser[]>([]);
const total = ref(0);
const loading = ref(false);

// 状态选项
const statusOptions = [
  { label: "未开始", value: 0 },
  { label: "进行中", value: 1 },
  { label: "已结束", value: 2 },
];

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true;
    const res = await queryByConsultantPage(queryForm.value as ByConsultantIdPageQuery);
    tableData.value = res.records;
    total.value = res.total;
  } catch (error) {
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

// 处理页码变化
const handleCurrentChange = (page: number) => {
  queryForm.value.pageNum = page;
  fetchData();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  queryForm.value.pageSize = size;
  queryForm.value.pageNum = 1;
  fetchData();
};
const handleSortChange = (sort: { prop: string; order: string }) => {
  console.log(sort, "sort");

  if (sort.prop === "progress") {
    queryForm.value.progressSort =
      sort.order === "ascending" ? "asc" : sort.order === "descending" ? "desc" : undefined;
    queryForm.value.pageNum = 1;
    queryForm.value.learningDurationSort = undefined;
  } else if (sort.prop === "learningDuration") {
    queryForm.value.learningDurationSort =
      sort.order === "ascending" ? "asc" : sort.order === "descending" ? "desc" : undefined;
    queryForm.value.pageNum = 1;
    queryForm.value.progressSort = undefined;
  }
  fetchData();
};
// 处理查询
const handleQuery = () => {
  queryForm.value.pageNum = 1;
  fetchData();
};

// 重置查询
const resetQuery = () => {
  queryForm.value = {
    courseId: undefined,
    consultantId:
      userStrore.userInfo.roles.includes("ADMIN") || userStrore.userInfo.roles.includes("ROOT")
        ? undefined
        : userStrore.userInfo.userId,
    status: undefined,
    learningDurationSort: undefined,
    progressSort: undefined,
    pageSize: 10,
    pageNum: 1,
  };
  fetchData();
};
const consultantOptions = ref<OptionType[]>([]);
const fetchConsultantOptions = async () => {
  const res = await UserAPI.getConsultantOptions();
  consultantOptions.value = res;
};
onMounted(() => {
  fetchData();
  queryCourseList();
  fetchCategories();
  fetchConsultantOptions();
});
</script>

<template>
  <div class="course-user-container">
    <!-- 查询条件 -->
    <el-card class="filter-container">
      <el-form :model="queryForm" inline>
        <el-form-item label="课程">
          <el-select
            v-model="queryForm.courseId"
            placeholder="请选择课程"
            clearable
            style="width: 250px"
          >
            <el-option
              v-for="item in courseList"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="课程分类">
          <el-cascader
            v-model="queryForm.categoryId"
            :options="categoryOptions"
            clearable
            :props="{
              value: 'id',
              label: 'name',
              children: 'children',
              emitPath: false,
              expandTrigger: 'click',
            }"
          />
        </el-form-item>
        <el-form-item v-hasPerm="['sys:course:consultant_search']" label="咨询师">
          <el-select
            v-model="queryForm.consultantId"
            placeholder="请选择咨询师"
            style="width: 150px"
            clearable
          >
            <el-option
              v-for="item in consultantOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学习状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-container">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <el-table-column prop="userName" label="用户名称" />
        <el-table-column prop="courseName" label="课程名称" />
        <el-table-column prop="categoryName" label="课程分类" />
        <el-table-column prop="progress" label="学习进度" sortable="custom">
          <template #default="{ row }">
            <el-progress :percentage="row.progress * 100" />
          </template>
        </el-table-column>
        <el-table-column prop="learningDuration" label="学习时长" sortable="custom">
          <template #default="{ row }">{{ Math.floor(row.learningDuration / 60) }}分钟</template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="row.status === 2 ? 'success' : row.status === 3 ? 'warning' : 'primary'">
              {{ statusOptions.find((item) => item.value === row.status)?.label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLearnTime" label="最后学习时间" />
        <el-table-column prop="currentChapter" label="当前章节" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.course-user-container {
  padding: 20px;

  .filter-container {
    margin-bottom: 20px;
  }

  .table-container {
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
